<template>
	<vue-content>
		<vue-header>
      <vue-header-form>
        <el-form :inline="true" :model="formFilter" ref="formFilter">
          <el-form-item label="选择机构" prop="institutionNo">
            <el-select v-model="formFilter.institutionNo" style="width:200px">
              <el-option 
                v-for="item in InstitutionList"
                :key="item.id"
                :label="item.institutionName"
                :value="item.institutionNo"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="模块名称" prop="moduleName">
            <el-input v-model.trim="formFilter.moduleName" style="width:150px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="SearchSubmit('formFilter')">查询</el-button>
            <el-button @click="resetForm('formFilter')">重置</el-button>
          </el-form-item>
        </el-form>
      </vue-header-form>
			<vue-header-button>
		        <el-button type="primary" @click="create">新增模块</el-button>
		    </vue-header-button>
		</vue-header>
		<vue-body>
	    	<el-table
	        v-loading.body="loading"
	        :data="tableData"
	        border
	        style="width: 100%">
	        <el-table-column
	          prop="institutionNo"
	          label="机构编号">
	        </el-table-column>
          <el-table-column
	          prop="moduleName"
	          label="模块名称">
	        </el-table-column>
          <el-table-column
	          label="模块状态">
            <template slot-scope="scope">
              {{ scope.row.status | status }}
            </template>
	        </el-table-column>
          <el-table-column
	          prop="moduleDesc"
	          label="模块描述">
	        </el-table-column>
	        <el-table-column
	          label="广告类型" width="140">
            <template slot-scope="scope">
              {{ scope.row.bannerType | bannerType }}
            </template>
	        </el-table-column>
	        <!-- <el-table-column
	          prop="seq"
	          label="排序" width="80">
	        </el-table-column> -->
	        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button-group>
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
            size="mini"
            type="primary"
            @click="handleDetail(scope.$index, scope.row, tableData)">详情</el-button>
            <el-button
            size="mini"
            @click="handleAdvert(scope.$index, scope.row)">广告设置</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row, tableData,'02')">删除</el-button>
            <el-button
              size="mini"
              v-if="scope.row.status == '00'"
              @click="abled(scope.row.id,'01')">启用</el-button>
            <el-button
              size="mini"
              type="danger"
              v-if="scope.row.status == '01'"
              @click="enabled(scope.row.id,'00')">禁用</el-button>
              </el-button-group>
          </template>
          </el-table-column>
	       </el-table>
	       <div class="back">
          <el-button type="primary" class="insProbtn" @click="back()">后退</el-button>
        </div>
	    </vue-body>
      <!-- <vue-footer style="padding: 5px 0;margin: 0 -5px;float:right;">
      <el-pagination
          :current-page.sync="currentPage"
          :page-size="10"
          layout="total, prev, pager, next"
          :total="pageSize">
        </el-pagination>
      </vue-footer> -->
	    <edit-module
	      ref="edit-module"
	      @close="editFinish"
	      :view="view"
	      v-if="view ==='create' || view ==='edit'"/>
      <edit-detail
        ref="edit-detail"
        @close="editFinish"
        :view="view"
        v-if="view ==='detail'"/>
   </vue-content>
</template>

<script>
import { queryInstitutionList} from "@/services/index";
import { query,change,queryDetail} from "@/services/module";
import {RequestError} from '@/services/errors'
import {deepClone} from '@/utilities/object'
import EditModule from './edit'
import EditDetail from './Detail'
export default {
  name: "ins-module",
  components: {EditModule,EditDetail},
  data: () => ({
      tableData: [],
      baseData:[],
      loading: false,
      institutionNo:"",
      InstitutionList:[],
      formFilter: {
        institutionNo: "",
        moduleName: ""
      },
      view: '',
  }),
  props: {},
  created(){
    // 取到路由带过来的参数 
    // let routerParams = this.$route.query.institutionNo;
    // 将数据放在当前组件的数据内
    // this.formFilter.institutionNo = routerParams;
    // this.institutionNo = routerParams;
    this.loadCategory();
  },
  mounted() {
  },
  methods: {
    async loadCategory () {
      try {
        let data = await queryInstitutionList();
        this.formFilter.institutionNo = data[0].institutionNo;
        this.InstitutionList = data;
        this.loadData();
      } catch (e) {
        if (e instanceof RequestError) {
          this.$alert(e.message, '提示', {
            type: 'error',
            confirmButtonText: '确定'
          })
        } else {
          throw e
        }
      }
      this.loading = false
    },
    async loadData () {
        this.loading = true
        try {
          let data = await query(Object.assign({currentPage: this.currentPage},{perPage:10}, this.formFilter))
//        console.log(data)
          this.tableData = data.moduleList
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
        this.loading = false
    },
    async create () {
        this.view = 'create'
        await this.$nextTick()
        this.$refs['edit-module'].institutionNo = this.institutionNo;
    },
    async handleEdit (index, data) {
        this.view = 'edit'
        await this.$nextTick()
        console.log(data)
        this.$refs['edit-module'].dialogFormVisible = true
        this.$refs['edit-module'].id = data.id
        this.$refs['edit-module'].institutionNo = data.institutionNo;
        this.$refs['edit-module'].formData = deepClone(data)
        this.$refs['edit-module'].imgShow = 'edit'
    },
    async handleAdvert (index, data) {
      this.$router.push({
        path: 'module/insAdvert', 
        name: 'insAdvert',
        query: { 
          institutionNo: data.institutionNo,
          moduleNo:data.moduleNo,
          bannerType:data.bannerType
        }
      })
    },
    async handleDetail (index, data) {
      this.view = 'detail'
      await this.$nextTick()
      this.$refs['edit-detail'].id = data.id
      this.$refs['edit-detail'].loadData()
    },
    async enabled (id,status) {
      try {
        // let insId = id.toString()
        await change({id:id,status:status})
        this.$message({
          type: 'success',
          message: '成功'
        })
        this.loadData()
      } catch (e) {
        if (e instanceof RequestError) {
          this.$alert(e.message, '提示', {
            type: 'error',
            confirmButtonText: '确定'
          })
        } else {
          throw e
        }
      }
    },
    async abled (id,status) {
      try {
        // let insId = id.toString()
        await change({id:id,status:status})
        this.$message({
          type: 'success',
          message: '成功'
        })
        this.loadData()
      } catch (e) {
        if (e instanceof RequestError) {
          this.$alert(e.message, '提示', {
            type: 'error',
            confirmButtonText: '确定'
          })
        } else {
          throw e
        }
      }
    },
    handleDelete (index, data, rows,status) {
        this.$confirm(`此操作将删除${data.moduleName}, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await change({id:data.id,status:status})
            this.$message({
              type: 'success',
              message: '已删除'
            })
            rows.splice(index, 1)
          } catch (e) {
            if (e instanceof RequestError) {
              this.$alert(e.message, '提示', {
                type: 'error',
                confirmButtonText: '确定'
              })
            } else {
              throw e
            }
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
    imgSrc(data){
      	return this.$store.state.imgUrl + data;
    },
    SearchSubmit () {
      this.currentPage = 1
      this.loadData()
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.currentPage = 1
      this.loadData()
    },
    editFinish (needRefresh) {
        this.view = ''
        if(needRefresh){
          this.$nextTick(() => {
            // dom元素更新后执行， 因此此处能正确打印出更改之后的值；
            this.loadData()
         	})
        }
    },
    back(){
    	this.$router.go(-1)
    }
  },
  filters: {
      status (value) {
        return {'00': '禁用', '01': '启用', '02': '删除'}[value]
      },
      bannerType (value) {
        return {'00': '推荐商品', '01': '图片广告','02':'商品列表'}[value]
      }
  }
};
</script>

<style>
	.el-table th>.cell{
		text-align: center;
	}
	.logoImg{
		height: 80px;
	}
	.insProbtn{
		float: right;
		margin-left: 30px;
  }
  .back{
    padding-top: 10px;
  }
</style>